package com.qidianit.mes.pro.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import com.qidianit.mes.pojo.pro.Process;
import com.qidianit.mes.pojo.Result;
import com.qidianit.mes.pro.mapper.ProcessMapper;
import com.qidianit.mes.pro.service.ProcessService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author: YKYB
 * @Date: 2025/9/17 18:02
 * @Description:
 */
@Service
public class ProcessServiceImpl implements ProcessService {

    @Autowired
    private ProcessMapper processMapper;

    @Override
    public Result<PageInfo<Process>> selectList(Process process, int pageNum, int pageSize) {
        //开启分页
        PageHelper.startPage(pageNum, pageSize);
        List<Process> processes = processMapper.selectList(process);
        return Result.success(new PageInfo<>(processes));
    }

    @Override
    public Result<Process> addProcess(Process process) {
        // 判重
        Process exist = processMapper.selectByProcessCode(String.valueOf(process.getProcessCode()));
        if (exist != null) {
            return Result.error("工序编码已存在");
        }
        processMapper.insert(process);
        return Result.success(process);
    }

    @Override
    public Result<Process> getByProcessCode(String code) {
        Process process = processMapper.selectByProcessCode(code);
        return process == null
                ? Result.error("工序编号不存在")
                : Result.success(process);
    }

    @Override
    public Result<?> deleteById(Long id) {
        int rows = processMapper.deleteById(id);
        return rows > 0
                ? Result.success("删除成功")
                : Result.error("工序不存在或已删除");
    }

    @Override
    public Result<?> batchDeleteByIds(List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            return Result.error("请选择要删除的工序");
        }
        int rows = processMapper.deleteByIds(ids);
        return rows > 0
                ? Result.success("批量删除成功")
                : Result.error("所选工序不存在或已删除");
    }

    @Override
    public Result<?> updateById(Process process) {

        Process dup = processMapper.selectByProcessCode(String.valueOf(process.getProcessCode()));
        if (dup != null && !dup.getId().equals(process.getId())) {
            return Result.error("工序编码已存在");
        }
        int rows = processMapper.updateById(process);
        return rows > 0
                ? Result.success("更新成功")
                : Result.error("更新失败");
    }

}
